<script setup lang="ts">
// 导入类型、组件、接口、模块
import type { PostUserPayloadType } from '@/api/user/types'
import type { FormRules, FormInstance } from 'element-plus'

import { reactive, ref } from 'vue'

// 表单数据（切记切记切记 全部用我给的单词）
const formData = reactive<PostUserPayloadType>({
	uname: '',
	pwd: '',
	mobile: '',
	avatar: ''
})
const checkMobile = (rule: any, value: any, callback: any) => {
	if (!value) return callback()

	if (/^1\d{10}$/.test(value)) {
		return callback()
	} else {
		return callback('手机号格式有误')
	}
}
const formRules = reactive<FormRules>({
	uname: [
		{ required: true, message: '用户名必须', trigger: 'blur' },
		{ min: 2, max: 8, message: '用户名至少2~8个字符', trigger: 'blur' }
	],
	pwd: [
		// { required: true, message: '密码必须', trigger: 'blur' },
		{ min: 6, max: 18, message: '用户名至少6~18个字符', trigger: 'blur' }
	],
	mobile: [{ validator: checkMobile, trigger: 'blur' }]
})

// 表单提交
const formRef = ref<FormInstance>()
const handleSubmit = () => {
	formRef.value?.validate((isSuccess) => {
		if (isSuccess) {
			console.log('立即更新：', formData)
		}
	})
}
const handleReset = () => {
	formRef.value!.resetFields()
}

// 对话框逻辑
const status = ref(false)
defineExpose({
	status, // 目的：控制dialog对话框隐藏显示
	formData // 目的：回显
})
</script>

<template>
	<div v-draggable="status">
		<el-dialog v-model="status" title="Tips" width="30%" :before-close="() => (status = false)">
			<!-- 标题 -->
			<template #header>
				<span>用户编辑</span>
			</template>
			<!-- 标题 -->

			<!-- 内容 -->
			<el-form v-if="status" label-width="80" size="large" :model="formData" :rules="formRules" ref="formRef">
				<el-form-item label="用户名" prop="uname">
					<el-input placeholder="请输入用户名" v-model="formData.uname" />
				</el-form-item>
				<el-form-item label="密码" prop="pwd">
					<el-input placeholder="请输入密码" v-model="formData.pwd" />
				</el-form-item>
				<el-form-item label="手机号" prop="mobile">
					<el-input placeholder="请输入手机号" v-model="formData.mobile" />
				</el-form-item>
				<el-form-item label="头像">
					{{ formData.avatar }}
					<img :src="formData.avatar" alt="" width="50" />
					<QfUpload />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleSubmit">立即更新</el-button>
					<el-button type="default" @click="handleReset">重置</el-button>
				</el-form-item>
			</el-form>
			<!-- 内容 -->
		</el-dialog>
	</div>
</template>

<style lang="scss" scoped>
.el-form {
	max-width: 600px;
}
</style>
